package com.pengpeng.sheepfoldmall.product.exception;

import com.pengpeng.common.exception.BizCodeEnum;
import com.pengpeng.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 异常处理类
 *
 * @RestControllerAdvice：@ControllerAdvice和@ResponseBody的合体
 *      basePackages属性：那些包下出现异常才会被该异常处理类处理
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.pengpeng.sheepfoldmall.product.controller")
public class SheepFoldMallExceptionAdvice {

    /**
     * 校验异常拦截
     * @ExceptionHandler(value = MethodArgumentNotValidException.class) 有针对的
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R validHandle(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{},异常类型为{}",e.getMessage(),e.getClass());
        Map<String,String> map = new HashMap<>();
        e.getBindingResult().getFieldErrors().forEach(item ->{
            String field = item.getField();
            String defaultMessage = item.getDefaultMessage();
            map.put(field,defaultMessage);
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data",map);
    }

    /**
     * 任意类型错误获取方法
     * Throwable任意类型异常
     * @param throwable
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R handle(Throwable throwable){
        log.error("错误",throwable);
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }
}
